package com.notice.service;

import com.notice.dao.MessageDao;
import com.notice.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class MessageService {
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private CommentService commentService;

    public int Add(Messages m){
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        m.setMtime(formatter.format(date));
        if (messageDao.add(m)==1) return m.getMid();
        return 0;
    }

    public boolean Update(Messages m){
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        m.setMtime(formatter.format(date));
        if (messageDao.update(m)==1) return true;
        return false;
    }

    public boolean delete(int mid){
        if (messageDao.delete(mid)==1){
            file file = new file();
            file.setMid(mid);
            deleteFile(file);
            Photo photo = new Photo();
            photo.setMid(mid);
            deletePhoto(photo);
            Comments comments = new Comments();
            comments.setMid(mid);
            commentService.Delete(comments);
            return true;
        }
        return false;
    }

    public List<Messages> findByKey(Messages m){
        return messageDao.find(m);
    }


    public int addphoto(Photo p){
        return messageDao.addPhoto(p);
    }

    public int addfile(file f){
        return messageDao.addFile(f);
    }

    public List<file> findFile(file f){
        return messageDao.findFile(f);
    }

    public List<Photo> findPhoto(Photo p){
        return messageDao.findPhoto(p);
    }

    public boolean deletePhoto(Photo p){
        if(messageDao.deletePhoto(p)==1){
            return true;
        }
        return false;
    }

    public boolean deleteFile(file f){
        if(messageDao.deleteFile(f)==1){
            return true;
        }
        return false;
    }

    public boolean photoChange(Photo p){
        return messageDao.updatePhoto(p)==1;
    }

    public boolean fileChange(file f){
        return messageDao.updateFile(f)==1;
    }

    public DetailMessage getDetail(int mid){
        DetailMessage detailMessage = new DetailMessage();
        Photo p = new Photo();
        p.setMid(mid);
        file f = new file();
        f.setMid(mid);
        detailMessage.setPhoto(findPhoto(p));
        detailMessage.setFile(findFile(f));
        return detailMessage;
    }
}
